package com.link.play.fit.ai.utils

import android.util.Log
import com.link.play.fit.ai.BuildConfig
import com.link.play.fit.ai.GlobalConfig.PACKAGE_NAME
import com.link.play.fit.ai.GlobalConfig.URL_EVENT
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import org.json.JSONObject
import java.io.IOException

object EventUtils {

    private val TAG = "EventUtils"
    private val url by lazy {
        val url = StringBuilder(
            "${URL_EVENT}/${
                PACKAGE_NAME.filter { it.isLowerCase() }.substring(4, 8)
            }sp"
        )
        url.append("?pkg=${PACKAGE_NAME}")
        url.toString()
    }

    fun event(
        action: String,
        value: String? = null,
        ext: JSONObject? = null,
        complete: (() -> Unit)? = null
    ) {

        val data = JSONObject()
            .put("action", action)
            .put("value", value)
            .put("ext", ext)

        val json = JSONObject()
            .put("data", data)
            .put("bp", DeviceHelps.getConfigParams())
            .toString()
        val body = AESHelps.encrypt(json)
            .toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())
        val client = OkHttpClient.Builder().apply {
            if (BuildConfig.DEBUG) {
                addInterceptor(HttpLoggingInterceptor().apply {
                    level = HttpLoggingInterceptor.Level.BODY
                })
            }
        }.build()

        val request = Request.Builder()
            .url(url)
            .post(body)
            .build()
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                if (BuildConfig.DEBUG) {
                    LogX.e(TAG, "onFailure action=$action url=$url e=$e")
                }
            }

            override fun onResponse(call: Call, response: Response) {
                if (response.code == 200 && response.isSuccessful) {
                    complete?.invoke()
                    if (BuildConfig.DEBUG) {
                        LogX.e(TAG, "onResponse 200 action=$action url=$url")
                    }
                }
            }
        })
    }
}